const app = getApp();
Component({
  properties: {
    receiveData: {
      type: JSON,
      value: '',
    },
    componentState:{
      type: Boolean,
      value: true,
    },
    formDetail:{
      type: JSON,
      value: '',
    },
    formListStyle: {
      type: JSON,
      value: '',
    },
    controlLimitState: {
      type: JSON,
      value: '',
    },
  },
  data: {
    setting: null, 
    formCommitItem:{},
    width:0,
    height:0,
    replyText:"",
    bannerList:null,
    conmmentList:[],
    filePreviewData:null,
  },
  ready: function () {
    let that = this;
    console.log("====form-item-formCommitItem======", that.data.receiveData);
    console.log("====form-item-formListStyle=====", that.data.formListStyle);
    console.log("====form-item-controlLimitState=====", that.data.controlLimitState);
    console.log("====form-item-formDetail=====", that.data.formDetail);
    console.log("====form-item-componentState=====", that.data.componentState);
    that.initData('init')
    that.setData({
      setting: app.globalData.setting,
    })
  },
  methods: {
    closeFilePreviewFun:function(){
        let that=this;
        console.log("=====onUnload=====");
        if(that.data.filePreviewData.fileType=='audio'){
            try{
                that.selectComponent("#audio").stopAudioFun();
            }catch(e){
                //TODO handle the exception
            }
        }else{
            try{
                that.selectComponent("#file_video").onStopPlay()
            }catch(e){
                //TODO handle the exception
            }
        }
        that.setData({filePreviewData:null})
    },
    filePreviewFun:function(e){
        let that=this;
        let fileItem = JSON.parse(e.currentTarget.dataset.item);
        console.log("===filePreviewFun===",e,fileItem);
        let fileUrl=fileItem.commitJson.upFile.value
        let filePreviewData={jsonData:{
            autoPlay: 0,
            height: "400px",
            id: "fileVideoComponent_"+fileItem.id,
            poster: "",
            source: fileUrl,
            type: "video_other",
            width: "750rpx",
        }}
        filePreviewData= Object.assign({},filePreviewData,{fileType:'video'})
        console.log("filePreviewData",filePreviewData)
        that.setData({filePreviewData:filePreviewData})
    },
    initData: function (data) {
      console.log("=========initData========", data)
      let that = this;
      let reqData;
      if (typeof (that.data.receiveData) == 'object') {
        reqData = that.data.receiveData
      } else {
        reqData = JSON.parse(that.data.receiveData)
      }
      // that.getCommentData(that.data.receiveData.id,1)
      reqData.showFunState = false;
      reqData.showFunBan = false;
      let commitJson = reqData.commitJson
      let bannerList = that.data.bannerList||[];
      let formListStyle = that.data.formListStyle
      for (let i in commitJson){
        if (commitJson[i]&&commitJson[i].type == 11){
            console.log("==console.log(commitJson[i])==",commitJson[i])
          bannerList[i]={
            androidTemplate:"form_more_banner",
            jsonData:{ 
               images: commitJson[i].value||'',
               height:'0.3',
            }
          }
        }
      }
      for(let j in bannerList){
          if(bannerList[j].jsonData.images.length!=0){
              for(let k=0;k<bannerList[j].jsonData.images.length;k++){
                  let url=bannerList[j].jsonData.images[k]
                  let obj={}
                  obj.width=150;
                  obj.imageUrl=url
                  bannerList[j].jsonData.images[k]=obj
              }
          }
      }
      console.log("=====bannerList======", bannerList)
      if (formListStyle&&formListStyle.length!=0){
        for (let i = 0; i < formListStyle.length; i++) {
          if (formListStyle[i].data.detailViewMagic && formListStyle[i].data.detailViewMagic.length != 0) {
            let detailViewMagic = formListStyle[i].data.detailViewMagic
            for (let j = 0; j < detailViewMagic.length; j++) {
              for (let key in bannerList) {
                if (detailViewMagic[j].propertieName == key) {
                  bannerList[key].jsonData.height = Math.abs(detailViewMagic[j].startPointY - detailViewMagic[j].endPointY) / Math.abs(detailViewMagic[j].startPointX - detailViewMagic[j].endPointX)
                }
              }
            }
          }
        }
      }
      that.setData({ bannerList: bannerList , formCommitItem: reqData, })
      console.log("=====databannerList======", that.data.bannerList,reqData)
      if (that.data.formListStyle) {
        that.setData({ width: Number(that.data.formListStyle.width) || 0 })
        that.setData({ height: Number(that.data.formListStyle.height) || 0 })
      }
    },
    replyTextStateFun:function(e){
      console.log("=========replyTextStateFun=====")
      let that = this;
      let type = e.currentTarget ? e.currentTarget.dataset.type : e;
      let state = (type == "show" ? true : false);
      that.data.formCommitItem.showFunBan = state
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    bindTextAreaBlur:function(e){
      console.log("=====bindTextAreaBlur====", e);
      let that=this;
      let value = e.detail.value;
      that.setData({ replyText: value})
    },
    replyTextData:function(){
      console.log("=====replyTextData====");
      let that = this;
      let params = {
        reply: that.data.replyText,
        commitId: that.data.formCommitItem.id
      }
      var customIndex = app.globalData.AddClientUrl("/super_shop_manager_reply_custom_form_commit.html", params)
      app.globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("setStateFun", res.data)
          that.showMoreFun("hidden")
          that.replyTextStateFun('hidden')
          if (res.data.errcode == 0) {
            that.data.formCommitItem.reply = res.data.relateObj.reply
            that.setData({ formCommitItem: that.data.formCommitItem })
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
            })
          }
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    setStateFun:function(e){
      console.log("=====setStateFun====", e);
      let that=this;
      let commitStatus = e.currentTarget.dataset.commitstatus;
      let params={
        commitStatus: commitStatus,
        commitId: that.data.formCommitItem.id
      }
      var customIndex = app.globalData.AddClientUrl("/super_shop_manager_set_commit_form_flag.html", params)
      app.globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("setStateFun", res.data)
          if (res.data.errcode==0){
            that.showMoreFun("hidden")
            that.data.formCommitItem.recordStatus = res.data.relateObj.recordStatus
            that.setData({ formCommitItem: that.data.formCommitItem})
          }else{
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
            })
          }
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    showMoreFun:function(e){
      console.log("=====showMoreFun====", e)
      let that = this;
      let type = e.currentTarget ? e.currentTarget.dataset.type:e;
      let state = (type == "show" ? true : false);
      that.data.formCommitItem.showFunState = state
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    showMore: function (e) {
      console.log("==showMore===", e)
      let that = this;
      let type = e.currentTarget.dataset.type;
      let length = e.currentTarget.dataset.length || 2;
      let state = (type == "show" ? true : false);
      let showNum = type == "show" ? length : 2;
      that.data.formCommitItem.showMoreState = state
      that.data.formCommitItem.showNum = showNum
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    calling: function (e) {
      console.log('====e===', e)
      let phoneNumber = e.currentTarget.dataset.phonenumber
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
    },
    checkFormDetail: function (data) {
      let that = this;
      console.log("====data===", data)
      let itemData=data.currentTarget.dataset.item ? JSON.parse(data.currentTarget.dataset.item) : {};
      let formId = itemData.id ? itemData.id : 0;
      let belongFormType = data.currentTarget.dataset.belongformtype ? data.currentTarget.dataset.belongformtype : 0;
      if (belongFormType == 0) {
        console.log("普通表单")
        wx.showActionSheet({
          itemList: ['查看用户提交的表单'],
          success: function (res) {
            console.log(res.tapIndex)
            if (!formId) {
              wx.showModal({
                title: '提示',
                content: '主人~该表单没有内容哦!',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            } else {
              let url = "check_form_detail.html?custom_form_commit_id=" + formId
              that.tolinkUrl(url)
            }
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        })
      } else {
        console.log("信息发布表单")
        if (!formId) {
          wx.showModal({
            title: '提示',
            content: '主人~该表单没有内容哦!',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else{
          let url =""
          if(app.globalData.loginUser&&itemData.commitPlatformUserId==app.globalData.loginUser.platformUser.id){
            console.log("发布人点击",)
            wx.showActionSheet({
              itemList: ['查看详情','编辑内容'],
              success: function (res) {
                console.log(res.tapIndex)
                if (!formId) {
                  wx.showModal({
                    title: '提示',
                    content: '主人~该表单没有内容哦!',
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }
                  })
                } else {
                  if(res.tapIndex==0){
                      url = "check_form_detail.html?custom_form_commit_id=" + formId;
                      that.tolinkUrl(url)
                  }else{
                      url = "form_detail.html?customFormId=" + itemData.belongFormId+"&userAddressCustomFormCommitId="+formId
                      that.tolinkUrl(url)
                  }
                }
              },
              fail: function (res) {
                console.log(res.errMsg)
              }
            })
          }else{
            console.log("其他用户点击查看详情")
            url = "check_form_detail.html?custom_form_commit_id=" + formId
            that.tolinkUrl(url)
          }
        }
        // {
        //   let url = "check_form_detail.html?custom_form_commit_id=" + formId
        //   that.tolinkUrl(url)
        // }
      }
    },
    // 定位
    clickCatch: function (e) {
      console.log("===定位====", e)
      let itemData = e.currentTarget.dataset.item;
      if(itemData&&itemData!=""){
          itemData=JSON.parse(itemData)
      }
      let latitude = itemData.latitude;
      let longitude = itemData.longitude;
      let name = itemData.value;
      let address = itemData.value
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        scale: 12,
        name: name,
        address: address
      })
    },
    //获取产品分类
    getOrganizesType: function (parentCategoryId, categoryId, callback) {
      var customIndex = app.globalData.AddClientUrl("/wx_get_categories_only_by_parent.html", { categoryId: parentCategoryId })
      app.globalData.showToastLoading('loading', true)
      var that = this
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("getOrganizesType", res.data)
          if (res.data.errcode == 0) {
            that.setData({ organizesType: res.data.relateObj })
          } else {
            that.setData({ organizesType: that.data.organizesType })
          }
          that.data.organizesType.unshift({ id: categoryId || parentCategoryId, name: "全部" })
          for (let i = 0; i < that.data.organizesType.length; i++) {
            that.data.organizesType[i].colorAtive = '#888';
          }
          that.data.organizesType[0].colorAtive = that.data.setting.platformSetting.defaultColor;
          that.data.organizesType[0].active = true;
          that.setData({ organizesType: that.data.organizesType })
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    toIndex() {
      app.globalData.toIndex()
    },
    tolinkUrl: function (data) {
      let linkUrl = data.currentTarget ? data.currentTarget.dataset.link : data;
      console.log("==linkUrl===", linkUrl)
      app.globalData.linkEvent(linkUrl)
    },
    onPullDownRefresh: function () {
      this.data.params.name = ""
      this.data.listPage.page = 1
      this.data.params.page = 1
      this.getData(this.data.params)
    },
    onReachBottom: function () {
      var that = this
      if (that.data.listPage.totalSize > that.data.listPage.curPage * that.data.listPage.pageSize) {
        that.data.listPage.page++
        that.data.params.page++
        that.getData(that.data.params);
      }
    },
    judgeFun:function(e){
        let that=this;
        console.log("==judgeFun==",e)
        let itemData=JSON.parse(e.currentTarget.dataset.itemdata);
        console.log("==itemData==",itemData)
        let type=e.currentTarget.dataset.type;
        let id=e.currentTarget.dataset.id;
        let listData=itemData.commitJson.moreImg.value
        let lengthStr=0;
        let count=0;
        if(type=='image'){
            lengthStr=listData.length;
        }else{
            lengthStr=1;
        }
        that.shareFormItemFun(itemData,type,function(res){
            count++;
            console.log("====count====",count,res)
            if(count==lengthStr){
                wx.hideLoading();
                let formCommitItem=that.data.formCommitItem;
                formCommitItem.viewCount++
                that.setData({formCommitItem:formCommitItem})
                that.getDetail(id)
                wx.showToast({
                  title: '素材已下载至手机相册',
                  icon: 'none',
                  duration: 2000
                })
            }else{
                wx.showLoading({
                    title: '素材已下载'+count+'/'+lengthStr,
                })
            }
        })
        // wx.showModal({
        //   title: '提示',
        //   content: '您确定要复制文本和下载图片吗？',
        //   success: function (res) {
        //     if (res.confirm) {  
        //       console.log('点击确认回调')
        //       that.shareFormItemFun(itemData)
        //     } else {   
        //       console.log('点击取消回调')
        //     }
        //   }
        // })
    },
    getDetail: function (formCommitId) {
      let that = this;
      let formDetailData = app.globalData.AddClientUrl("/wx_get_custom_form_commit.html", { formCommitId: formCommitId }, 'get')
      wx.request({
        url: formDetailData.url,
        data: formDetailData.params,
        header: app.globalData.headerPost,
        method: 'get',
        success: function (res) {
          console.log("====success====", res)
          if (res.data.errcode == 0) {
            let data=res.data.relateObj
            wx.hideLoading()
          }
        }
      })
    },
    // 朋友圈样式方法
    shareFormItemFun:function(itemData,type,callback){
        let that=this;
        let fileList=itemData.commitJson.moreImg.value;
        let value=itemData.commitJson.title.value;
        let vauleStr= getApp().globalData.toRichFun(value)
        console.log("====vauleStr====",vauleStr)
        if(type=='video'){
            fileList=itemData.commitJson.upFile.value.split(',')
        }
        console.log("shareFormItemFun",itemData,fileList);
        if(type=='text'){
            if(value){
                wx.setClipboardData({
                  data: vauleStr,
                  success: function (res) {
                    wx.getClipboardData({
                      success: function (res) {
                        wx.showToast({
                          title: '文案已复制',
                          icon: 'none',
                          duration: 1000
                        });
                      }
                    });
                  }
                });
            }
        }else{
            wx.authorize({
             scope: 'scope.writePhotosAlbum',
             success:function(e){
                console.log("success",e)
                setTimeout(function(){
                    if(fileList&&fileList.length!=0){
                        for (let i = 0; i < fileList.length;i++){
                          that.downloadFileFun(fileList[i], type, callback)
                        }
                    }
                },1000)
             },
             fail:function(e){
                console.log("fail",e)
             },
            })
        }
    },
    downloadFileFun: function(url,type,callback){　　　　　　　　　　　　　　　　//触发函数
        console.log(url,type)
        let that=this;
        let fileUrl=''
        if(url&&url.imageUrl&&(!type||type=='img'||type=='image')){
            fileUrl=url.imageUrl.replace('http://','https://');
        }else{
            fileUrl=url.replace('http://','https://');
        }
        wx.showLoading({
            title: '文件下载中..',
        })
        wx.downloadFile({
          url: fileUrl,　　　　　　　//需要下载的图片url
          success: function (res) {　　　　　　　　　　　　//成功后的回调函数
              if(!type||type=='img'||type=='image'){
                  that.saveImageToPhotosAlbumFun(res,callback)
              }else if(type||type=='video'){
                  that.saveVideoToPhotosAlbumFun(res,callback)
              }
            // wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
            //   filePath: res.tempFilePath,
            //   success(res) {
            //     wx.hideLoading();
            //     wx.showToast({
            //       title: '素材已下载至手机相册',
            //       icon: 'none',
            //       duration: 2000
            //     })
            //   },
            //   fail: function (err) {
            //     wx.hideLoading();
            //     if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
            //       wx.openSetting({
            //         success(settingdata) {
            //           console.log(settingdata)
            //           if (settingdata.authSetting['scope.writePhotosAlbum']) {
            //             console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
            //           } else {
            //             console.log('获取权限失败，给出不给权限就无法正常使用的提示')
            //           }
            //         }
            //       })
            //     }
            //   }
            // })
          }
        });
    },
    saveImageToPhotosAlbumFun:function(res,callback){
        wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
          filePath: res.tempFilePath,
          success(res) {
              console.log("====saveImageToPhotosAlbumFun===",res)
              if(callback){
                  callback(res)
              }
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
    },
    saveVideoToPhotosAlbumFun:function(res,callback){
        wx.saveVideoToPhotosAlbum({　　　　　　　　　//保存到本地
          filePath: res.tempFilePath,
          success(res) {
            if(callback){
                callback(res)
            }
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
    },
    lookBigImage: function (e) {
      console.log("111111111", e.currentTarget.dataset);
      let imgSrc = e.currentTarget.dataset.imageurl;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let PostImageSrc = [];
      console.log(imgSrc);
      if(imgSrc&&imgSrc!=""){
          imgSrc=JSON.parse(imgSrc)
      }
      for (let i = 0; i < imgSrc.length; i++) {
        imgArray.push(imgSrc[i].imageUrl);
        PostImageSrc.push(imgSrc[i].imageUrl.replace(/http/, "https"));
      } 
      console.log(PostImageSrc);
      if (!imgSrc) {
        return;
      }
      wx.previewImage({
        current: imgArray[index],
        // 当前显示图片的http链接
        urls: imgArray // 需要预览的图片http链接列表

      });
    },
    //获取评论数据
    getCommentData: function (customFormInstanceId, page) {
      let that = this;
      let data = {
        customFormInstanceId: customFormInstanceId,
        page: page
      }
      let customIndex = getApp().globalData.AddClientUrl("/get_news_bbs_comments.html", data)
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('====sssssss===', res)
          let conmmentList=that.conmmentList
          if (page == 1) {
            conmmentList=res.data.relateObj.result
          } else {
            console.log("====more page====");
            conmmentList=conmmentList.concat(res.data.relateObj.result)
          }
          that.setData({conmmentList:conmmentList})
          console.log("==that.conmmentList===",that.conmmentList);
        },
        fail: function (res) {//获取数据失败就会进入这个方法
          wx.hideLoading()
        }
      })
    },
    toCommentFun:function(e){
        let that=this;
        let itemData=e.currentTarget.dataset.itemdata||''
        let type=e.currentTarget.dataset.type||''
        that.triggerEvent('toComment', {itemData:itemData,type:type})
    },
  }
})